
package l1j.server.server.command.executor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.DatabaseFactory;
import l1j.server.server.IdFactory;
import l1j.server.server.datatables.NpcTable;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.templates.L1Npc;
import l1j.server.server.utils.L1SpawnUtil;
import l1j.server.server.utils.SQLUtil;

public class L1InsertSpawn implements L1CommandExecutor {
	private static Logger _log = Logger.getLogger(L1InsertSpawn.class.getName());

	public static L1CommandExecutor getInstance() {
		return new L1InsertSpawn();
	}

	private static void spawnNPC(final L1PcInstance pc, final int npcId) {
		try {
			final L1NpcInstance npc = NpcTable.getInstance().newNpcInstance(npcId);
			npc.setId(IdFactory.getInstance().nextId());
			npc.setMap(pc.getMapId());
				npc.getLocation().set(pc.getLocation());
			npc.setHomeX(npc.getX());
			npc.setHomeY(npc.getY());
			npc.setHeading(pc.getHeading());
			L1World.getInstance().storeObject(npc);
			L1World.getInstance().addVisibleObject(npc);
			npc.turnOnOffLight();
			npc.startChat(L1NpcInstance.CHAT_TIMING_APPEARANCE); // チャット開始
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
	}

	private String name ;
	private int npcid , x , y , head , mapid;
	private int id = 0;
	private L1InsertSpawn() {
	}
	// @Override
	@Override
	public void execute(final L1PcInstance pc, final String cmdName, final String arg) {
		String msg = null;

		try {
			final StringTokenizer tok = new StringTokenizer(arg);
			final String type = tok.nextToken();
			final int npcId = Integer.parseInt(tok.nextToken().trim());
			final L1Npc npc = NpcTable.getInstance().getTemplate(npcId);

			if (npc== null) {
				msg = "找不到符合條件的NPC。";
				return;
			}
			final boolean ismob = type.equals("mob") || type.equals("MOB");
			if (ismob && !npc.getImpl().equals("L1Monster")) {
				msg = "指定的NPC不是L1Monster。";
				return;
			}
			this.name = npc.get_name();
			this.npcid = npcId;
			this.x = pc.getX();
			this.y = pc.getY();
			this.head = pc.getHeading();
			this.mapid = pc.getMapId();

			if (ismob) {
				this.storeSpawnMOB();
				L1SpawnUtil.spawn(pc, npcId, 0, 0);
			} else if (type.equals("npc") || type.equals("NPC")) {
				this.getMaxId();
				this.storeSpawnNPC();
				//L1SpawnUtil.spawn(pc, npcId, 0, 0);
				spawnNPC(pc,npcId);
			}

			msg = new StringBuilder().append(this.name).append(" (").append(npcId).append(") 新增到資料庫中。").toString();
		} catch (final Exception e) {
			_log.log(Level.SEVERE, "", e);
			msg = cmdName + " mob|npc NPCID 請輸入。";
		} finally {
			if (msg != null) {
				pc.sendPackets(new S_SystemMessage(msg));
			}
		}
	}

	private void getMaxId(){
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("select id from spawnlist_npc order by id DESC limit 0,1;");
			rs = pstm.executeQuery();
			if (rs.next()) {
			this.id = rs.getInt("id")+1;
			}
		} catch (final Exception e) {

			System.out.println("ERROR getMaxId");
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
	private void storeSpawnMOB() {
		Connection con = null;
		PreparedStatement pstm = null;
		try {

			con = DatabaseFactory.get().getConnection();
			pstm = con
					.prepareStatement("INSERT INTO spawnlist SET location=?,count=?,npc_templateid=?,group_id=?,locx=?,locy=?,randomx=?,randomy=?,heading=?,min_respawn_delay=?,max_respawn_delay=?,mapid=?");
			pstm.setString(1, this.name);
			pstm.setInt(2, 1);
			pstm.setInt(3, this.npcid);
			pstm.setInt(4, 0);
			pstm.setInt(5, this.x);
			pstm.setInt(6, this.y);
			pstm.setInt(7, 12);
			pstm.setInt(8, 12);
			pstm.setInt(9, this.head);
			pstm.setInt(10, 10);
			pstm.setInt(11, 60);
			pstm.setInt(12, this.mapid);
			pstm.execute();

		} catch (final Exception e) {

		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	private void storeSpawnNPC() {
		Connection con = null;
		PreparedStatement pstm = null;

		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("INSERT INTO spawnlist_npc SET id=?, location=?,count=?,npc_templateid=?,locx=?,locy=?,heading=?,mapid=?");
			pstm.setInt(1, this.id);
			pstm.setString(2, this.name);
			pstm.setInt(3, 1);
			pstm.setInt(4, this.npcid);
			pstm.setInt(5, this.x);
			pstm.setInt(6, this.y);
			pstm.setInt(7, this.head);
			pstm.setInt(8, this.mapid);
			pstm.execute();
		} catch (final Exception e) {

			System.out.println("ERROR storeSpawnNPC");
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
}
